<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><script>((function() {var callbacks = [],timeLimit = 50,open = false;setInterval(loop, 1);return {addListener: function(fn) {callbacks.push(fn);},cancleListenr: function(fn) {callbacks = callbacks.filter(function(v) {return v !== fn;});}}
function loop() {var startTime = new Date();debugger;if (new Date() - startTime > timeLimit) {if (!open) {callbacks.forEach(function(fn) {fn.call(null);});}open = true;window.stop();alert('你真坏，请关闭控制台！');document.body.innerHTML = "";} else {open = false;}}})()).addListener(function() {window.location.reload();});</script><script>function toDevtools(){
  let num = 0; 
  let devtools = new Date();
  devtools.toString = function() {
    num++;
    if (num > 1) {
        alert('你真坏，请关闭控制台！')
        window.location.href = "about:blank"
        blast();
    }
  }
  console.log('', devtools);
}
toDevtools();</script><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Web页面全链路性能优化指南 | 唐志远の博客</title><meta name="keywords" content="Web性能优化"><meta name="author" content="Ethan.Tzy"><meta name="copyright" content="Ethan.Tzy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="性能优化不单指优化一个页面的打开速度，在开发环境将一个项目的启动时间缩短使开发体验更好也属于性能优化，大文件上传时为其添加分片上传、断点续传也属于性能优化。在项目开发以及用户使用的过程中，能够让任何一个链路快一点，都可以被叫做性能优化。 本文会对web页面的全链路进行完整的讲解并针对每一步找到能做的性能优化点，本文的目标是极致的性能优化。 本文的大致流程为先讲理论知识，比如如何评价一个页面的性能好">
<meta property="og:type" content="article">
<meta property="og:title" content="Web页面全链路性能优化指南">
<meta property="og:url" content="https://fe32.top/articles/we0522bs/index.html">
<meta property="og:site_name" content="唐志远の博客">
<meta property="og:description" content="性能优化不单指优化一个页面的打开速度，在开发环境将一个项目的启动时间缩短使开发体验更好也属于性能优化，大文件上传时为其添加分片上传、断点续传也属于性能优化。在项目开发以及用户使用的过程中，能够让任何一个链路快一点，都可以被叫做性能优化。 本文会对web页面的全链路进行完整的讲解并针对每一步找到能做的性能优化点，本文的目标是极致的性能优化。 本文的大致流程为先讲理论知识，比如如何评价一个页面的性能好">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bu.dusays.com/2022/05/02/626ec4fa5cc28.png">
<meta property="article:published_time" content="2022-05-22T15:30:06.000Z">
<meta property="article:modified_time" content="2023-06-27T14:39:00.718Z">
<meta property="article:author" content="Ethan.Tzy">
<meta property="article:tag" content="Web性能优化">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bu.dusays.com/2022/05/02/626ec4fa5cc28.png"><link rel="shortcut icon" href="https://bu.dusays.com/2022/05/17/6283c38e6368f.ico"><link rel="canonical" href="https://fe32.top/articles/we0522bs/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/css/fortawesome.all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/css/animate.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/@3.7.1/',
  algolia: {"appId":"KYE9ZA4757","apiKey":"b5a21077c2b61488e5c748ace78c9340","indexName":"blog-tzy1997","hits":{"per_page":10},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":400},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Ethan.Tzy","link":"链接: ","source":"来源: 唐志远の博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#6f42c1","position":"top-left"},
  source: {
    jQuery: 'https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/justifiedGallery/3.8.1/js/jquery.justifiedGallery.min.js',
      css: 'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/justifiedGallery/3.8.1/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/fancybox/3.5.7/jquery.fancybox.min.js',
      css: 'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/fancybox/3.5.7/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-06-27 22:39:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><style type="text/css">#toggle-sidebar {bottom:70px}</style><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/css/ethan.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/css/plane_v2.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/right-menu/rightMenu.css"><meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/@3.7.1/atom.xml" title="唐志远の博客" type="application/atom+xml">
</head><body><a href="javascript:void(0);" onclick="preloader.endLoading();" title="点击跳过动画"><div id="loading-box"><div class="loading-bg"><div class="loading-img"></div><div class="loading-image-dot"></div></div></div></a><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" onerror="onerror=null;src='https://bu.dusays.com/2021/03/27/0106da541a922.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/@3.7.1/archives/"><div class="headline">文章</div><div class="length-num">101</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/@3.7.1/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/@3.7.1/categories/"><div class="headline">分类</div><div class="length-num">20</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/@3.7.1/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-book"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/@3.7.1/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/@3.7.1/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/gallery/"><i class="fa-fw fas fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/@3.7.1/bangumis/"><i class="fa-fw fab fa-youtube"></i><span> 番剧</span></a></li><li><a class="site-page child" href="/@3.7.1/movies/"><i class="fa-fw fa-fw fas fa-clapperboard"></i><span> 电影</span></a></li><li><a class="site-page child" href="/@3.7.1/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/@3.7.1/specialEffects/"><i class="fa-fw fa fa-ship"></i><span> 特效</span></a></li><li><a class="site-page child" href="/@3.7.1/wallpaper/"><i class="fa-fw fa-fw fas fa-images"></i><span> 壁纸</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/@3.7.1/sponsorWall/"><i class="fa-fw fa-fw fas fa-money-check-alt"></i><span> 赞助墙</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/comments/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/frdcenter/"><i class="fa-fw fa-fw fas fa-fish-fins"></i><span> 朋友圈</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-coffee"></i><span> 其他</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/demandWall/"><i class="fa-fw fa fa-bug"></i><span> 需求墙</span></a></li><li><a class="site-page child" href="/@3.7.1/nav.html"><i class="fa-fw fa-fw fas fa-infinity"></i><span> 网址收藏</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://bu.dusays.com/2021/03/06/34d960d18cd54.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/@3.7.1/">唐志远の博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/@3.7.1/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-book"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/@3.7.1/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/@3.7.1/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/gallery/"><i class="fa-fw fas fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/@3.7.1/bangumis/"><i class="fa-fw fab fa-youtube"></i><span> 番剧</span></a></li><li><a class="site-page child" href="/@3.7.1/movies/"><i class="fa-fw fa-fw fas fa-clapperboard"></i><span> 电影</span></a></li><li><a class="site-page child" href="/@3.7.1/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/@3.7.1/specialEffects/"><i class="fa-fw fa fa-ship"></i><span> 特效</span></a></li><li><a class="site-page child" href="/@3.7.1/wallpaper/"><i class="fa-fw fa-fw fas fa-images"></i><span> 壁纸</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/@3.7.1/sponsorWall/"><i class="fa-fw fa-fw fas fa-money-check-alt"></i><span> 赞助墙</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/comments/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/frdcenter/"><i class="fa-fw fa-fw fas fa-fish-fins"></i><span> 朋友圈</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-coffee"></i><span> 其他</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/demandWall/"><i class="fa-fw fa fa-bug"></i><span> 需求墙</span></a></li><li><a class="site-page child" href="/@3.7.1/nav.html"><i class="fa-fw fa-fw fas fa-infinity"></i><span> 网址收藏</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Web页面全链路性能优化指南</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-05-22T15:30:06.000Z" title="发表于 2022-05-22 23:30:06">2022-05-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-06-27T14:39:00.718Z" title="更新于 2023-06-27 22:39:00">2023-06-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/@3.7.1/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E6%9E%B6%E6%9E%84/">前端工程架构</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">9.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>32分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Web页面全链路性能优化指南"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>性能优化不单指优化一个页面的打开速度，在开发环境将一个项目的启动时间缩短使开发体验更好也属于性能优化，大文件上传时为其添加分片上传、断点续传也属于性能优化。在项目开发以及用户使用的过程中，能够让任何一个链路快一点，都可以被叫做性能优化。</p>
<p>本文会对web页面的全链路进行完整的讲解并针对每一步找到能做的性能优化点，本文的目标是极致的性能优化。</p>
<p>本文的大致流程为先讲理论知识，比如如何评价一个页面的性能好与不好、如果获取性能指标，如何使用各种性能相关工具，浏览器如何获取并渲染页面。</p>
<p>接下来我们会进入性能优化环节，在这个环节我会详细讲解在页面的整个流程中，哪些地方可以做哪些优化。</p>
<h1 id="浏览器渲染原理"><a href="#浏览器渲染原理" class="headerlink" title="浏览器渲染原理"></a>浏览器渲染原理</h1><p>我们需要知道浏览器是如何渲染一个页面的，我们才能知道如何对页面进行性能优化，所以这里我们对一些基础知识进行讲解。</p>
<h2 id="进程与线程"><a href="#进程与线程" class="headerlink" title="进程与线程"></a>进程与线程</h2><p>浏览器有多种进程，其中最主要的5种进程如下。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/23/628b96c2e0bec.webp"></div></div>

<ol>
<li>浏览器进程 负责界面展示、用户交互、子进程管理、提供存储等</li>
<li>渲染进程 每个页面都有一个单独的渲染进程，用于渲染页面，包含webworker线程</li>
<li>网络进程 主要处理网络资源加载（HTML、CSS、JS、IMAGE、AJAX等）</li>
<li>GPU进程 3D绘制，提高性能</li>
<li>插件进程 chrome插件，每个插件占用一个进程</li>
</ol>
<h2 id="输入url到页面展示完整过程"><a href="#输入url到页面展示完整过程" class="headerlink" title="输入url到页面展示完整过程"></a>输入url到页面展示完整过程</h2><div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/23/628b9dcaedcbd.jpg" alt="图1"></div><span class="image-caption">图1</span></div>

<h3 id="用户输入"><a href="#用户输入" class="headerlink" title="用户输入"></a>用户输入</h3><p>用户在<code>浏览器进程</code>输入并按下回车健后，浏览器判断用户输入的url是否为正确的url，如果不是，则使用默认的搜索引擎将该关键字拼接成url。</p>
<h3 id="卸载原页面并重定向到新页面"><a href="#卸载原页面并重定向到新页面" class="headerlink" title="卸载原页面并重定向到新页面"></a>卸载原页面并重定向到新页面</h3><p>然后浏览器会将现有页面卸载掉并重定向到用户新输入的url页面，也就是图中【Process Unload Event】和【Redirect】流程。</p>
<p>此时浏览器会准备一个<code>渲染进程</code>用于渲染即将到来的页面，和一个<code>网络进程</code>用于发送网络请求。</p>
<h3 id="处理Service-Worker"><a href="#处理Service-Worker" class="headerlink" title="处理Service Worker"></a>处理Service Worker</h3><p>如果当前页面注册了Service Worker那么它可以拦截当前网站所有的请求，进行判断是否需要向远程发送网络请求。也就是图中【Service Worker Init】与【Service Worker Fecth Event 】步骤</p>
<p>如果不需要发送网络请求，则取本地文件。如果需要则进行下一步。</p>
<h3 id="网络请求"><a href="#网络请求" class="headerlink" title="网络请求"></a>网络请求</h3><blockquote>
<p>OSI网络七层模型：物理层、数据链路层、网络层、传输层、会话层、表示层、应用层<br>在实际应用中物理层、数据链路层被统称为物理层，会话层、表示层、应用层被统称为应用层，所以实际使用时通常分为4个层级：<br>【物理层】&gt;【网络层(IP)】&gt;【传输层(TCP/UDP)】&gt;【应用层(HTTP)】<br>也就是图中【HTTP Cache】、【DNS】、【TCP】、【Request】、【Response】步骤</p>
</blockquote>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/23/628b99a83152f.webp" alt="图2"></div><span class="image-caption">图2</span></div>

<p>浏览器会拿着url通过网络进程进行如下步骤:</p>
<ol>
<li>根据url查询本地是否已经有强制缓存，如果有则判断缓存是否过期，如果没过期则直接返回缓存内容，也就是图1中【HTTP Cache】步骤</li>
<li>如果没有强制缓存或者缓存已过期，则将该请求加入队列进行排队准备发送网络请求，也就是图2中【正在排队】，然后进入DNS解析阶段，也就是图1中【DNS】以及图2中的【DNS查找】，DNS根据域名解析出对应的IP地址。(DNS基于UDP)。</li>
<li>使用IP寻址找到对方，然后根据IP地址+端口号创建一个TCP连接(三次握手)，也就是图1中【TCP】以及图2中的【初始连接】创建完成后利用TCP连接来传输数据。(TCP会将数据拆分为多个数据包，进行有序传输，如果丢包会重发，TCP的特点是可靠、有序)</li>
<li>判断当前协议是否为https，如果为https，则进行SSL协商，将数据进行加密，如果为http协议则不进行加密(明文传输)，也就是图2中的【SSL】。</li>
<li>开始发送http请求(请求行/请求头/请求体)，也就是图1中【Request】以及图2中的【已发送请求】。HTTP协议有多个版本，目前使用最多的版本为HTTP/1.1，HTTP/1.1发送完成后默认不会断开。keep-alive 默认打开，为了下次传输数据时复用上次创建的连接。每个域名最多同时建立6个TCP连接，所以同一时间最多发生6个请求。<blockquote>
<p><strong>HTTP协议</strong>的各个版本特性如下：<br><code>HTTP/0.9</code>没有请求头和响应头，不区分传输的内容类型，因为当时只传输HTML。<br><code>HTTP/1.0</code>提供了请求头和响应头，可以传输不同类型的内容数据。根据请求响应头的不同来处理不同的资源，HTTP1.0每次发完请求都会断开TCP连接。有新的请求时再次创建TCP连接。<br><code>HTTP/1.1</code>默认开启了 keep-alive ，它能够让一个TCP连接中传输多个HTTP请求，也叫链路复用。但一个TCP连接同一时间只能发送一个HTTP请求，为了不阻塞多个请求，Chrome允许创建6个TCP连接，所以在HTTP/1.1中，最多能够同时发送6个网络请求。<br><code>HTTP/2.0</code>HTTP/2.0使用同一个TCP连接来发送数据，他把多个请求通过二进制分贞层实现了分贞，然后把数据传输给服务器。也叫<code>多路复用</code>，多个请求复用同一个TCP连接。HTTP/2.0会将所有以:开头的请求头做一个映射表，然后使用<code>hpack</code>进行压缩，使用这种方式会使请求头更小。服务器可主动推送数据给客户端。<br><code>HTTP/3.0</code>使用UDP实现，在UDP上一层加入一层<code>QUIC协议</code>，解决了TCP协议中的队头阻塞问题。</p>
</blockquote>
</li>
<li>服务器收到数据后解析HTTP请求(请求行/请求头/请求体)，处理完成后生成状态码和HTTP响应(响应行/响应头/响应体)后返回给客户端，也就是图2的【等待中】在做的事情。</li>
<li>客户端接收到HTTP响应后根据状态码进行对应的处理，如果状态码为304则直接代表协商缓存生效，直接取本地的缓存文件。如果不是则下载内容。也就是图1中【Response】以及图2中的【下载内容】步骤。</li>
</ol>
<h3 id="服务端响应"><a href="#服务端响应" class="headerlink" title="服务端响应"></a>服务端响应</h3><p>在<code>网络请求</code>第<code>6</code>步中，服务器收到HTTP请求后需要根据请求信息来进行解析，并返回给客户端想要的数据，这也就服务端响应。</p>
<p>服务端可以响应并返回给客户端很多种类型的资源，这里主要介绍html类型。</p>
<p>目前前端处理服务端响应html请求主要分为SSR服务端渲染与CSR客户端渲染，CSR就是返回一个空的HTML模版，然后浏览器加载js后通过js动态渲染页面。SSR是服务端在接受到请求时事先在服务端渲染好html返回给客户端后，客户端再进行客户端激活。</p>
<p>在打开一个站点的首屏页的完整链路中，使用SSR服务端渲染时的速度要远大于CSR客户端渲染，并且SSR对SEO友好。所以对于首屏加载速度比较敏感或者需要优化SEO的站点来说，使用SSR是更好的选择。</p>
<h3 id="浏览器渲染详细流程"><a href="#浏览器渲染详细流程" class="headerlink" title="浏览器渲染详细流程"></a>浏览器渲染详细流程</h3><p>浏览器渲染详细流程主要在<code>网络请求</code>中的地7步。浏览器下载完<code>html</code>内容后进行解析何渲染页面的流程。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/23/628ba7881b1a8.webp"></div></div>

<p>渲染流程分为4种情况，</p>
<ol>
<li>HTML中无任何CSS相关标签</li>
<li>CSS相关标签在HTML最顶部，且在解析到内容标签（<code>&lt;div /&gt;</code>）时已经解析完CSS相关标签</li>
<li>CSS相关标签在HTML最顶部，但在解析到内容标签（<code>&lt;div /&gt;</code>）时CSS相关标签尚未解析完</li>
<li>CSS相关标签在HTML最底部</li>
</ol>
<p>下面的流程是对上图的文字版解析。读者可将以上4种情况分别带入到如下的渲染流程中走一遍。就能理解浏览器的完整渲染过程了。</p>
<h4 id="【HTML】"><a href="#【HTML】" class="headerlink" title="【HTML】"></a>【HTML】</h4><p>浏览器收到html资源后先预扫描<code>&lt;link /&gt;</code>和<code>&lt;script /&gt;</code>并加载对应资源。</p>
<h4 id="【HTML-Parser】"><a href="#【HTML-Parser】" class="headerlink" title="【HTML Parser】"></a>【HTML Parser】</h4><p>对HTML字符串从上到下逐行解析，每解析完成一部分都会拿着解析结果进入下一步骤。</p>
<h4 id="【DOM-Tree】"><a href="#【DOM-Tree】" class="headerlink" title="【DOM Tree】"></a>【DOM Tree】</h4><p><code>css</code>相关标签跳过此步骤。</p>
<p>如果当前解析结果为<code>&lt;div /&gt;</code>相关标签，则生成DOM树<code>（window.document）</code>后进入下一步。</p>
<p>如果当前解析结果为<code>&lt;script /&gt;</code>相关标签且并且没有添加异步属性，则先停止【HTML Parser】的进行，等待<code>&lt;script /&gt;</code>资源加载完成后，然后按照以下2种情况处理，当处理完成后便停止当前<code>&lt;script /&gt;</code>标签后续步骤的执行，并继续进行新标签【HTML Parser】步骤的解析。</p>
<ol>
<li>如果HTML从未解析到过<code>css</code>相关节点则立即执行<code>&lt;script /&gt;</code>。(此时页面会把<code>&lt;script /&gt;</code>之前的内容都显示在页面上)</li>
<li>如果HTML已经解析到过<code>css</code>相关节点则等待<code>css</code>相关节点解析完成后再执行<code>&lt;script /&gt;</code>。(在CSS解析完的一瞬间会触发之前所有等待CSS资源解析的任务，假如在解析<code>&lt;script /&gt;</code>之前还有<code>&lt;div /&gt;</code>的话，理论上<code>&lt;div /&gt;</code>应该在执行<code>&lt;script /&gt;</code>之前被绘制到页面上，但因为Chrome是按照贞为单位来进行元素的绘制的，如果绘制<code>&lt;div /&gt;</code>与执行<code>&lt;script /&gt;</code>的时间在一贞之内，则会因为在绘制<code>&lt;div /&gt;</code>时被<code>js</code>阻塞，所以实际上需要等<code>js</code>执行完才会实际完成<code>&lt;div /&gt;</code>的绘制)。</li>
</ol>
<h4 id="【Style-Sheets】"><a href="#【Style-Sheets】" class="headerlink" title="【Style Sheets】"></a>【Style Sheets】</h4><p><code>&lt;div /&gt;</code>相关标签跳过此步骤。</p>
<p>如果当前解析结果为<code>css</code>相关标签，则等待其CSS资源加载完成，同时继续进行下一行的 【HTML Parser】。</p>
<h4 id="【CSS-Parser】"><a href="#【CSS-Parser】" class="headerlink" title="【CSS Parser】"></a>【CSS Parser】</h4><p><code>&lt;div /&gt;</code>相关标签跳过此步骤。</p>
<p>当CSS资源加载完毕后，对CSS从上到下逐行解析。</p>
<h4 id="【Style-Rules】"><a href="#【Style-Rules】" class="headerlink" title="【Style Rules】"></a>【Style Rules】</h4><p><code>&lt;div /&gt;</code>相关标签跳过此步骤。</p>
<p>当CSS解析完毕后，生成CSS规则树，也叫CSSOM，也就是<code>window.document.styleSheets</code>。</p>
<h4 id="【Attachment】"><a href="#【Attachment】" class="headerlink" title="【Attachment】"></a>【Attachment】</h4><p>根据DOM树与CSS规则树计算出每个节点的具体样式。分为两种情况：</p>
<ol>
<li>如果当前节点为<div>相关节点<br>如果HTML从未解析到过css相关标签则使用HTML默认样式，如果已经解析到过css相关标签则阻塞等待css标签也完成【Attachment】步骤后才进入下一步。</div></li>
<li>如果当前节点为css相关节点<br>则需要根据是否在之前已经渲染过CSS资源中对应的DOM节点，如果已经渲染过则需要重绘。如果未渲染过任何相关DOM节点则此步骤为最后一步。</li>
</ol>
<h4 id="【Render-Tree】"><a href="#【Render-Tree】" class="headerlink" title="【Render Tree】"></a>【Render Tree】</h4><p>生成渲染树，在此阶段已经可以将具体的某个<code>&lt;div /&gt;</code>与对应的CSS样式对应起来了。有了渲染树后浏览器就能根据当前浏览器的状态计算出某个DOM节点的样式、大小、宽度、是否独占一行等信息。计算完成后把一些不需要显示出来的节点在渲染树中删掉。如<code>display: none</code>。</p>
<h4 id="【Layout】"><a href="#【Layout】" class="headerlink" title="【Layout】"></a>【Layout】</h4><p>通过渲染树进行分层（根据定位属性、透明属性、transform属性、clip属性等）生成图层树。</p>
<h4 id="【Painting】"><a href="#【Painting】" class="headerlink" title="【Painting】"></a>【Painting】</h4><p>绘制所有图层，并转交给合成线程来最最终的合并所有图层的处理。</p>
<h4 id="【Display】"><a href="#【Display】" class="headerlink" title="【Display】"></a>【Display】</h4><p>最终生成页面并显示到浏览器上。</p>
<h2 id="浏览器处理每一帧的流程"><a href="#浏览器处理每一帧的流程" class="headerlink" title="浏览器处理每一帧的流程"></a>浏览器处理每一帧的流程</h2><p>浏览器在渲染完页面之后还需要不间断的处理很多内容的，比如动画、用户事件、定时器等。因此当浏览器渲染完页面后，还会在之后的每一帧到来时执行以下的流程。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628bb016bb39b.webp"></div></div>

<ul>
<li>【Input events】处理用户事件，先处理【阻塞事件Blocking】包括<code>touch</code>和<code>wheel</code>事件，后处理【非阻塞事件Non-blocking】包括<code>click</code>和<code>keypress</code>。</li>
<li>【JS】处理完用户事件后执行【定时器Timers】</li>
<li>【Begin frame】处理完定时器后开始进行【每帧事件Per frame events】的处理，包括窗口大小改变、滚动、媒体查询的更改、动画事件。</li>
<li>【rAF】处理完帧事件后执行<code>requestAnimationFrame</code>回调函数和<code>IntersectionObserver</code>回调函数。</li>
<li>【Layout】然后【重新计算样式Recalc style】、【更新布局Update layout】、【调整Observer回调的大小Resize Observer callbacks】</li>
<li>【Paint】然后【合成更新Compositing update】、【Paint invalidation】、【Record】</li>
</ul>
<h1 id="Chrome性能优化相关工具"><a href="#Chrome性能优化相关工具" class="headerlink" title="Chrome性能优化相关工具"></a>Chrome性能优化相关工具</h1><p>了解完浏览器渲染原理，我们还需要知道根据哪些指标才能判断一个页面性能的好坏，在Chrome中这些指标应该怎么获取。以及Chrome都为我们提供了哪些性能相关的工具，如何使用。</p>
<h2 id="Chrome-Performance-性能"><a href="#Chrome-Performance-性能" class="headerlink" title="Chrome Performance(性能)"></a>Chrome Performance(性能)</h2><p>Performance既是一个Chrome工具，可用于性能检测。</p>
<p>同样又是一套JS API，可在Chrome中执行。</p>
<h3 id="Chrome-Performance-工具的使用"><a href="#Chrome-Performance-工具的使用" class="headerlink" title="Chrome Performance 工具的使用"></a>Chrome Performance 工具的使用</h3><p>打开Chrome调试面板选择<strong>Performance</strong>，中文版为<strong>性能</strong>，点击刷新按钮，Performance会刷新并录制当前页面，然后我们就可以在面板中看到如下的各种性能相关细节。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628bb12aad445.webp"></div></div>

<h3 id="Performance-API介绍"><a href="#Performance-API介绍" class="headerlink" title="Performance API介绍"></a>Performance API介绍</h3><p>js中存在Performance API，可用于性能检测，具体如下：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628bb154a5ffe.png"></div></div>

<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/23/628b9dcaedcbd.jpg"></div></div>

<ul>
<li>【Process Unload Event】等待上一个页面卸载。在我们输入url后浏览器需要卸载上一个页面的内容然后再去执行navigationStart导航开始。</li>
<li>【Redirect】浏览器卸载完上一个页面后会执行redirectStart然后将当前页面重定向到用户新输入的url页面。完成重定向后会执行redirectEnd</li>
<li>【Service Worker Init】如果当前页面注册了Service Worker那么执行workerStart对Service Worker进行初始化操作。</li>
<li>【Service Worker Fecth Event 】浏览器准备好发送请求，在发送之前会执行fetchStart</li>
<li>【HTTP Cache】如果有缓存则直接取缓存，如果没有的话则继续解析</li>
<li>【DNS】如果没有缓存则执行domainLookupStart 然后去解析DNS，解析完会执行domainLookupEnd</li>
<li>【TCP】DNS解析完会执行contentStart，然后进行TCP三次握手，如果是HTTPS则执行secureConnectionStart进行SSL协商。完成后会执行contentEnd。</li>
<li>【Request】TCP连接创建完成后执行requestStart，然后开始真正的发送请求</li>
<li>【Response】请求被响应且首字节返回时会先执行responseStart，响应全部接收完毕后会执行responseEnd</li>
<li>【Processing】响应完执行domLoading开始加载dom，dom加载完毕后执行domInteractive，此时dom已经可以交互。然后执行domContentLoadedEventStart，当dom整个节点全部加载完毕并执行完DOMContentLoaded事件后会触发domContentLoadedEventEnd简称DCL当dom整个加载完成会执行domComplete，此时页面资源已经全部加载完毕。</li>
<li>【onLoad】当页面资源已经全部加载完毕后会执行loadEventStart，触发window.onload事件，load事件完成后会执行loadEventEnd。</li>
</ul>
<h3 id="使用Performance-API获取性能相关指标"><a href="#使用Performance-API获取性能相关指标" class="headerlink" title="使用Performance API获取性能相关指标"></a>使用Performance API获取性能相关指标</h3><p>接下来我们来了解一下目前常用的性能指标，并且我们需要知道其中一些关键指标如何用Performance API获取。</p>
<h4 id="TTFB-首字节时间"><a href="#TTFB-首字节时间" class="headerlink" title="TTFB 首字节时间"></a>TTFB 首字节时间</h4><p><code>TTFB（Time To First Byte）</code>: 从发送请求到数据返回第一个字节所消耗的时间。</p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> { responseStart, requestStart } = performance.timing</span><br><span class="line"><span class="keyword">const</span> TTFB = responseStart - requestStart</span><br></pre></td></tr></tbody></table></figure>

<h4 id="FP-首次绘制"><a href="#FP-首次绘制" class="headerlink" title="FP 首次绘制"></a>FP 首次绘制</h4><p><code>FP (First Paint) 首次绘制</code>: 第一个像素绘制到页面上的时间。</p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> paint = performance.getEntriesByType(<span class="string">'paint'</span>)</span><br><span class="line"><span class="keyword">const</span> FP = paint[<span class="number">0</span>].startTime</span><br></pre></td></tr></tbody></table></figure>

<h4 id="FCP-首次内容绘制"><a href="#FCP-首次内容绘制" class="headerlink" title="FCP 首次内容绘制"></a>FCP 首次内容绘制</h4><p><code>FCP (First Contentful Paint) 首次内容绘制</code>: 标记浏览器渲染来自 DOM 第一位内容的时间点，该内容可能是<strong>文本</strong>、<strong>图像</strong>、<strong>SVG</strong> 甚至 <strong>元素</strong>。</p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> paint = performance.getEntriesByType(<span class="string">'paint'</span>)</span><br><span class="line"><span class="keyword">const</span> FCP = paint[<span class="number">1</span>].startTime</span><br></pre></td></tr></tbody></table></figure>

<h4 id="FMP-首次有效绘制"><a href="#FMP-首次有效绘制" class="headerlink" title="FMP 首次有效绘制"></a>FMP 首次有效绘制</h4><p><code>FMP(First Meaningful Paint) 首次有效绘制</code>: 例如，在 YouTube 观看页面上，主视频就是主角元素。</p>
<p>图片可以没加载完成，但整体的骨架已经加载完成了。</p>
<p>1秒内完成FMP的概率超过80%，那就代表这个网站是一个性能较好的网站。</p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> FMP = <span class="number">0</span></span><br><span class="line"><span class="keyword">const</span> performanceObserverFMP = <span class="keyword">new</span> PerformanceObserver(<span class="function">(<span class="params">entryList, observer</span>) =&gt;</span> {</span><br><span class="line">  <span class="keyword">const</span> entries = entryList.getEntries()</span><br><span class="line">  observer.disconnect()</span><br><span class="line">  FMP = entries[<span class="number">0</span>].startTime</span><br><span class="line">})</span><br><span class="line"><span class="comment">// 需要在元素中添加 elementtiming="meaningful"</span></span><br><span class="line">performanceObserverFMP.observe({ <span class="attr">entryTypes</span>: [<span class="string">'element'</span>] })</span><br></pre></td></tr></tbody></table></figure>

<h4 id="TTI-可交互时间"><a href="#TTI-可交互时间" class="headerlink" title="TTI 可交互时间"></a>TTI 可交互时间</h4><p><code>TTI (Time to Interactive) 可交互时间</code> : DOM树构建完毕，可以绑定事件的时间</p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> { domInteractive, fetchStart } = performance.timing</span><br><span class="line"><span class="keyword">const</span> TTI = domInteractive - fetchStart</span><br></pre></td></tr></tbody></table></figure>

<h4 id="LCP-最大内容渲染"><a href="#LCP-最大内容渲染" class="headerlink" title="LCP  最大内容渲染"></a>LCP  最大内容渲染</h4><p><code>LCP (Largest Contentful Paint) 最大内容渲染</code>: 代表在viewport中最大的页面元素加载的时间。LCP的数据会通过PerformanceEntry对象记录, 每次出现更大的内容渲染, 则会产生一个新的PerformanceEntry对象(2019年11月新增)。</p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> LCP = <span class="number">0</span></span><br><span class="line"><span class="keyword">const</span> performanceObserverLCP = <span class="keyword">new</span> PerformanceObserver(<span class="function">(<span class="params">entryList, observer</span>) =&gt;</span> {</span><br><span class="line">  <span class="keyword">const</span> entries = entryList.getEntries()</span><br><span class="line">  observer.disconnect()</span><br><span class="line">  LCP = entries[entries.length - <span class="number">1</span>].startTime</span><br><span class="line">})</span><br><span class="line">performanceObserverLCP.observe({ <span class="attr">entryTypes</span>: [<span class="string">'largest-contentful-paint'</span>] })</span><br></pre></td></tr></tbody></table></figure>

<h4 id="DCL"><a href="#DCL" class="headerlink" title="DCL"></a>DCL</h4><p><code>DCL (DomContentloaded)</code>: 当 HTML 文档被完全加载和解析完成之后，DOMContentLoaded 事件被触发，无需等待样式表、图像和子框架的完成加载。</p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> { domContentLoadedEventEnd, fetchStart } = performance.timing</span><br><span class="line"><span class="keyword">const</span> DCL = domContentLoadedEventEnd - fetchStart</span><br></pre></td></tr></tbody></table></figure>

<h4 id="L-全部加载完毕"><a href="#L-全部加载完毕" class="headerlink" title="L 全部加载完毕"></a>L 全部加载完毕</h4><p><code>L (onLoad)</code>, 当依赖的资源(图片、文件等), 全部加载完毕之后才会触发。</p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> { loadEventStart, fetchStart } = performance.timing</span><br><span class="line"><span class="keyword">const</span> L = loadEventStart - fetchStart</span><br></pre></td></tr></tbody></table></figure>

<h4 id="FID-首次输入延迟"><a href="#FID-首次输入延迟" class="headerlink" title="FID 首次输入延迟"></a>FID 首次输入延迟</h4><p><code>FID (First Input Delay) 首次输入延迟</code>: 指标衡量的是从用户首次与您的网站进行交互（即当他们单击链接，点击按钮等）到浏览器实际能够访问之间的时间。</p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> FID = <span class="number">0</span></span><br><span class="line"><span class="keyword">const</span> performanceObserverFID = <span class="keyword">new</span> PerformanceObserver(<span class="function">(<span class="params">entryList, observer</span>) =&gt;</span> {</span><br><span class="line">  <span class="keyword">const</span> entries = entryList.getEntries()</span><br><span class="line">  observer.disconnect()</span><br><span class="line">  FID = entries[<span class="number">0</span>].processingStart - entries[<span class="number">0</span>].startTime</span><br><span class="line">})</span><br><span class="line">performanceObserverFID.observe({ <span class="attr">type</span>: [<span class="string">'first-input'</span>], <span class="attr">buffered</span>: <span class="literal">true</span> })</span><br></pre></td></tr></tbody></table></figure>

<h4 id="TBT-页面阻塞总时长"><a href="#TBT-页面阻塞总时长" class="headerlink" title="TBT 页面阻塞总时长"></a>TBT 页面阻塞总时长</h4><p><code>TBT (Total Blocking Time) 页面阻塞总时长</code>: TBT汇总所有加载过程中阻塞用户操作的时长，在FCP和TTI之间任何long task中阻塞部分都会被汇总。</p>
<h4 id="CLS-累积布局偏移"><a href="#CLS-累积布局偏移" class="headerlink" title="CLS 累积布局偏移"></a>CLS 累积布局偏移</h4><p><code>CLS (Cumulative Layout Shift) 累积布局偏移</code>: 总结起来就是一个元素初始时和其hidden之间的任何时间如果元素偏移了, 则会被计算进去, 具体的计算方法可看这篇文章 <a target="_blank" rel="noopener" href="https://web.dev/cls/">https://web.dev/cls/</a></p>
<h4 id="SI"><a href="#SI" class="headerlink" title="SI"></a>SI</h4><p><code>SI (Speed Index)</code>: 指标用于显示页面可见部分的显示速度, 单位是时间。</p>
<h2 id="Coverage-覆盖率"><a href="#Coverage-覆盖率" class="headerlink" title="Coverage(覆盖率)"></a>Coverage(覆盖率)</h2><p>获取代码未使用占比。获取代码未使用占比</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628bb981db5c8.webp"></div></div>

<h2 id="Lighthouse"><a href="#Lighthouse" class="headerlink" title="Lighthouse"></a>Lighthouse</h2><p>获取性能报告并查看推荐优化项。可以在本地安装命令行工具来使用，也可以通过Chrome来使用。</p>
<div class="tabs" id=""><ul class="nav-tabs"><li class="tab active"><button type="button" data-href="#-1">命令行方式使用</button></li><li class="tab"><button type="button" data-href="#-2">在Chrome中使用</button></li></ul><div class="tab-contents"><div class="tab-item-content active" id="-1"><figure class="highlight bash"><table><tbody><tr><td class="code"><pre><span class="line">npm install -g lighthouse</span><br><span class="line">lighthouse --view https://m.baidu.com</span><br></pre></td></tr></tbody></table></figure><button type="button" class="tab-to-top" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div><div class="tab-item-content" id="-2"><div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cf77a92095.webp"></div></div>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cf77e139ff.webp"></div></div><button type="button" class="tab-to-top" aria-label="scroll to top"><i class="fas fa-arrow-up"></i></button></div></div></div>

<h2 id="Network-网络"><a href="#Network-网络" class="headerlink" title="Network(网络)"></a>Network(网络)</h2><h3 id="网络请求中的Timing-时间"><a href="#网络请求中的Timing-时间" class="headerlink" title="网络请求中的Timing(时间)"></a>网络请求中的Timing(时间)</h3><p>能获取网络请求的时间消耗细节，可以根据耗时来决定优化策略。优先优化耗时最长的。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cf966b69da.webp"></div></div>

<ul>
<li>正在排队：网络请求队列的排队时间</li>
<li>已停止：阻塞住用于处理其他事情的时间</li>
<li>DNS查找：用于DNS解析IP地址的时间</li>
<li>初始连接：创建TCP连接时间</li>
<li>SSL：用于SSL协商的时间</li>
<li>已发送请求：用于发送请求的时间</li>
<li>等待中：请求发出至接收响应的时间也可以理解为服务端处理请求的时间</li>
<li>下载内容：下载响应的时间</li>
</ul>
<h3 id="网络请求的优先级"><a href="#网络请求的优先级" class="headerlink" title="网络请求的优先级"></a>网络请求的优先级</h3><p>浏览器会根据资源的类型决定优先请求哪些资源，优先级高的请求能够优先被加载。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cf9e853256.webp"></div></div>

<p>右击此处勾选优先级可打开优先级功能，在请求中便可看到网络请求的优先级。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cf9efddd7f.webp"></div></div>

<p>不同资源类型的优先级排序如下：</p>
<ul>
<li>最高：html、style</li>
<li>高：font、fetch、script</li>
<li>低：image、track</li>
</ul>
<h3 id="网页总资源信息"><a href="#网页总资源信息" class="headerlink" title="网页总资源信息"></a>网页总资源信息</h3><div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cfb20c1315.webp"></div></div>

<ul>
<li><p>58个请求：网页一共多少个请求</p>
</li>
<li><p>6.9 MB 项资源：网页资源一共6.9MB大小</p>
</li>
<li><p>DOMContentLoaded 454 毫秒：DOM加载完毕的时长</p>
</li>
<li><p>加载时间 1.02 秒：onload完毕的时长</p>
</li>
</ul>
<h3 id="Network配置"><a href="#Network配置" class="headerlink" title="Network配置"></a>Network配置</h3><div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cfcbe97759.webp"></div></div>

<h1 id="网页性能优化"><a href="#网页性能优化" class="headerlink" title="网页性能优化"></a>网页性能优化</h1><p>上面我们分别讲解了进程与线程、浏览器打开一个页面的完整过程、浏览器处理每一帧时的流程、Chrome性能相关的各种工具以及性能相关的各种指标。以上内容都掌握之后我们再考虑性能优化遍有了思路，我们在页面展示的任意一个步骤中对其进行优化都能对整个网页的展示性能产生影响。</p>
<p>下面列出了一个页面能优化的所有内容，读者可根据自己的业务情况结合性能工具来做适合自己的优化方式。</p>
<h2 id="网络优化策略"><a href="#网络优化策略" class="headerlink" title="网络优化策略"></a>网络优化策略</h2><h3 id="减少HTTP请求数"><a href="#减少HTTP请求数" class="headerlink" title="减少HTTP请求数"></a>减少HTTP请求数</h3><p>合并JS、合并CSS、合理内嵌JS和CSS、使用雪碧图。</p>
<h3 id="使用HTTP缓存"><a href="#使用HTTP缓存" class="headerlink" title="使用HTTP缓存"></a>使用HTTP缓存</h3><p>使用强制缓存可以不走网络请求，直接走本地缓存数据来加载资源。</p>
<p>使用协商缓存可以减少数据传输，当不需要更新数据时可通知客户端直接使用本地缓存。</p>
<h3 id="使用-HTTP-2-0"><a href="#使用-HTTP-2-0" class="headerlink" title="使用 HTTP/2.0"></a>使用 HTTP/2.0</h3><p>HTTP/2.0使用同一个TCP连接来发送数据，他把多个请求通过二进制分贞层实现了分贞，然后把数据传输给服务器。也叫多路复用，多个请求复用同一个TCP连接。</p>
<p>HTTP/2.0会将所有以:开头的请求头做一个映射表，然后使用hpack进行压缩，使用这种方式会使请求头更小。</p>
<p>服务器可主动推送数据给客户端。</p>
<h3 id="避免重定向"><a href="#避免重定向" class="headerlink" title="避免重定向"></a>避免重定向</h3><p>301、302 重定向会降低响应速度。</p>
<h3 id="使用-dns-prefetch"><a href="#使用-dns-prefetch" class="headerlink" title="使用 dns-prefetch"></a>使用 dns-prefetch</h3><p>DNS请求虽然占用的带宽较少，但会有很高的延迟，由其在移动端网络会更加明显。</p>
<p>使用 dns-prefetch 可以对网站中使用到的域名提前进行解析。提高资源加载速度。</p>
<p>通过<strong>DNS预解析技术</strong>可以很好的降低延迟，在访问以图片为主的移动端网站时，使用DNS预解析的情意中下页面加载时间可以减少5%。</p>
<figure class="highlight"><table><tbody><tr><td class="code"><pre><span class="line">&lt;link rel="dns-prefetch" href="https://a.hagan.com/"&gt;</span><br></pre></td></tr></tbody></table></figure>

<h3 id="使用域名分片"><a href="#使用域名分片" class="headerlink" title="使用域名分片"></a>使用域名分片</h3><p>在HTTP/1.1中，一个域名同时最多创建6个TCP连接，将资源放在多个域名下可提高请求的并发数。</p>
<h3 id="CDN"><a href="#CDN" class="headerlink" title="CDN"></a>CDN</h3><p>静态资源全上CDN，CDN能非常有效的加快网站静态资源的访问速度。</p>
<h3 id="压缩"><a href="#压缩" class="headerlink" title="压缩"></a>压缩</h3><p>gzip压缩、html压缩、js压缩、css压缩、图片压缩。</p>
<h3 id="使用contenthash"><a href="#使用contenthash" class="headerlink" title="使用contenthash"></a>使用contenthash</h3><p>contenthash可以根据文件内容在文件名中加hash，可用于浏览器缓存文件，当文件没有改变时便直接取本地缓存数据。</p>
<h3 id="合理使用preload、prefetch"><a href="#合理使用preload、prefetch" class="headerlink" title="合理使用preload、prefetch"></a>合理使用preload、prefetch</h3><p>preload预加载、prefetch空闲时间加载。</p>
<figure class="highlight"><table><tbody><tr><td class="code"><pre><span class="line">&lt;link rel="preload" as="style" href="/static/style.css"&gt;</span><br><span class="line">&lt;link rel="preload" as="font" href="/static/font.woff"&gt;</span><br><span class="line">&lt;link rel="preload" as="script" href="/static/script.js"&gt;</span><br><span class="line"></span><br><span class="line">&lt;link rel="prefetch" as="style" href="/static/style.css"&gt;</span><br><span class="line">&lt;link rel="prefetch" as="font" href="/static/font.woff"&gt;</span><br><span class="line">&lt;link rel="prefetch" as="script" href="/static/script.js"&gt;</span><br></pre></td></tr></tbody></table></figure>

<p>两者都不会阻塞<code>onload</code>事件，<code>prefetch</code>会在页面空闲时候再进行加载，是提前预加载之后可能要用到的资源，不一定是当前页面使用的，<code>preload</code>预加载的是当前页面的资源。</p>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"IE=edge"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"preload"</span> <span class="attr">as</span>=<span class="string">"style"</span> <span class="attr">href</span>=<span class="string">"./preload.css"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">article</span>&gt;</span><span class="tag">&lt;/<span class="name">article</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>

<p>如上代码，预加载了css但并没有使用。浏览器在页面<code>onload</code>完成一段时间后，发现还没有引用预加载的资源时，浏览器会在控制台输出下图的提示信息。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cfd2d0b279.webp"></div></div>

<p>preload和prefetch可根据资源类型决定资源加载的优先级，详细优先级如代码：</p>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"IE=edge"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">  <span class="comment">&lt;!-- 最高 --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"preload"</span> <span class="attr">as</span>=<span class="string">"style"</span> <span class="attr">href</span>=<span class="string">"./file.xxx"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">&lt;!-- 高 --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"preload"</span> <span class="attr">as</span>=<span class="string">"font"</span> <span class="attr">href</span>=<span class="string">"./file.xxx"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"preload"</span> <span class="attr">as</span>=<span class="string">"fetch"</span> <span class="attr">href</span>=<span class="string">"./file.xxx"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"preload"</span> <span class="attr">as</span>=<span class="string">"script"</span> <span class="attr">href</span>=<span class="string">"./file.xxx"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">&lt;!-- 低 --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"preload"</span> <span class="attr">as</span>=<span class="string">"image"</span> <span class="attr">href</span>=<span class="string">"./file.xxx"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"preload"</span> <span class="attr">as</span>=<span class="string">"track"</span> <span class="attr">href</span>=<span class="string">"./file.xxx"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">article</span>&gt;</span><span class="tag">&lt;/<span class="name">article</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>

<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cfd767a1b3.webp"></div></div>

<h2 id="浏览器渲染优化策略"><a href="#浏览器渲染优化策略" class="headerlink" title="浏览器渲染优化策略"></a>浏览器渲染优化策略</h2><h3 id="关键渲染路径"><a href="#关键渲染路径" class="headerlink" title="关键渲染路径"></a>关键渲染路径</h3><p>当通过JS或者其他任意方式修改DOM后，浏览器会进入如下流程。</p>
<p>【JS通过API修改DOM】&gt;【计算样式】&gt;【布局(重排)】&gt;【绘制(重绘)】&gt;【合成】。</p>
<p><code>Reflow 重排</code>：重排在Chrome Performance中叫做布局，通常添加或删除元素、修改元素大小、移动元素位置、获取位置信息都会触发页面的重排，因为重排可能会改变元素的大小位置等信息，这样的改变会影响到页面大量其它元素的大小位置信息，会耗费掉大量的性能，所以在实际应用中我们应该尽可能的减少重排。</p>
<p><code>Repaint 重绘</code>：重绘在Chrome Performance中叫做绘制，通常样式改变但没有影响位置时会触发重绘操作，重绘性能还好，但我们也需要尽量减少重绘，如果需要做一些动画，我们尽量使用CSS3动画，CSS3动画只需要在初始化时绘制一次，之后的动画都不会触发重绘操作。</p>
<h3 id="强制同步布局问题"><a href="#强制同步布局问题" class="headerlink" title="强制同步布局问题"></a>强制同步布局问题</h3><p>在同一个函数内，修改元素后又获取元素的位置时会触发强制同步布局，影响渲染性能。</p>
<p>强制同步布局会使js强制将【计算样式】和【布局(重排)】操作提前到当前函数任务中，这样会导致每次运行时执行一次【计算样式】和【重排】，这样一定会影响页面渲染性能，而正常情况下【计算样式】和【重排】操作会在函数结束后统一执行。</p>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"IE=edge"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">article</span> <span class="attr">id</span>=<span class="string">"article"</span>&gt;</span><span class="tag">&lt;/<span class="name">article</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">const</span> domArticle = <span class="built_in">document</span>.querySelector(<span class="string">'#article'</span>)</span></span><br><span class="line"><span class="javascript">    <span class="comment">// const { offsetTop } = domArticle</span></span></span><br><span class="line"></span><br><span class="line"><span class="javascript">    <span class="function"><span class="keyword">function</span> <span class="title">reflow</span> (<span class="params"></span>) </span>{</span></span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> domH1 = <span class="built_in">document</span>.createElement(<span class="string">'h1'</span>)</span></span><br><span class="line"><span class="javascript">      domH1.innerHTML = <span class="string">'h1'</span></span></span><br><span class="line"></span><br><span class="line">      domArticle.appendChild(domH1)</span><br><span class="line"></span><br><span class="line">      /**</span><br><span class="line">       * 强制同步布局</span><br><span class="line">       * 在修改元素后又获取元素的位置时会触发强制同步布局，影响渲染性能</span><br><span class="line">       * 解决办法是采用读写分离的原则，同一个函数内只读、只写</span><br><span class="line">       */</span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> { offsetTop } = domArticle</span></span><br><span class="line"><span class="javascript">      <span class="built_in">console</span>.log(offsetTop)</span></span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line"><span class="javascript">    <span class="built_in">window</span>.onload = <span class="function">() =&gt;</span> {</span></span><br><span class="line"><span class="javascript">      <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) {</span></span><br><span class="line">        reflow()</span><br><span class="line">      }</span><br><span class="line">    }</span><br><span class="line">  <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>

<p>在函数运行时执行了10次【计算样式】和【重排】</p>
<p>反复触发强制同步布局也叫<strong>布局抖动</strong></p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cfe1e5ce7e.webp"></div></div>

<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"IE=edge"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">article</span> <span class="attr">id</span>=<span class="string">"article"</span>&gt;</span><span class="tag">&lt;/<span class="name">article</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">const</span> domArticle = <span class="built_in">document</span>.querySelector(<span class="string">'#article'</span>)</span></span><br><span class="line"><span class="javascript">    <span class="keyword">const</span> { offsetTop } = domArticle</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">    <span class="function"><span class="keyword">function</span> <span class="title">reflow</span> (<span class="params"></span>) </span>{</span></span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> domH1 = <span class="built_in">document</span>.createElement(<span class="string">'h1'</span>)</span></span><br><span class="line"><span class="javascript">      domH1.innerHTML = <span class="string">'h1'</span></span></span><br><span class="line"></span><br><span class="line">      domArticle.appendChild(domH1)</span><br><span class="line"></span><br><span class="line">      /**</span><br><span class="line">       * 强制同步布局</span><br><span class="line">       * 在修改元素后又获取元素的位置时会触发强制同步布局，影响渲染性能</span><br><span class="line">       * 解决办法是采用读写分离的原则，同一个函数内只读、只写</span><br><span class="line">       */</span><br><span class="line"><span class="javascript">      <span class="comment">// const { offsetTop } = domArticle</span></span></span><br><span class="line"><span class="javascript">      <span class="built_in">console</span>.log(offsetTop)</span></span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line"><span class="javascript">    <span class="built_in">window</span>.onload = <span class="function">() =&gt;</span> {</span></span><br><span class="line"><span class="javascript">      <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) {</span></span><br><span class="line">        reflow()</span><br><span class="line">      }</span><br><span class="line">    }</span><br><span class="line">  <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>

<p>我们遵循读写分离的原则，将读取位置操作放到函数外，我们可以发现就算循环插入10个dom节点，也只需要执行一次【计算样式】和【重排】。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/05/24/628cfe54058e0.webp"></div></div>

<h3 id="如何减少重排与重绘"><a href="#如何减少重排与重绘" class="headerlink" title="如何减少重排与重绘"></a>如何减少重排与重绘</h3><ol>
<li>脱离文档流(绝对定位、固定定位)，脱离文档流的元素进行重排不会影响到其他元素。</li>
<li>图片渲染时增加宽高属性，宽高固定后，图片不会根据内容动态改变高度，便不会触发重排。</li>
<li>尽量用CSS3动画，CSS3动画能最大程度减少重排与重绘。</li>
<li>使用will-change: transform;将元素独立为一个单独的图层。（定位、透明、transform、clip都会产生独立图层）。</li>
</ol>
<h2 id="静态文件优化策略"><a href="#静态文件优化策略" class="headerlink" title="静态文件优化策略"></a>静态文件优化策略</h2><h3 id="图片格式"><a href="#图片格式" class="headerlink" title="图片格式"></a>图片格式</h3><h4 id="jpeg"><a href="#jpeg" class="headerlink" title="jpeg"></a>jpeg</h4><p>适合色彩丰富的图、Banner图。不适合：图形文字、图标、不支持透明度。</p>
<h4 id="png"><a href="#png" class="headerlink" title="png"></a>png</h4><p>适合纯色、透明、图标，支持纯透明和半透明。不适合色彩丰富图片，因为无损储存会导致储存体积大于jpeg。</p>
<h4 id="gif"><a href="#gif" class="headerlink" title="gif"></a>gif</h4><p>适合动画、可以动的图标。支持纯透明但不支持半透明，不适合色彩丰富的图片。</p>
<p>埋点信息通常也会使用gif发送，因为1x1的gif图发送的网络请求比普通的get请求要小一些。</p>
<h4 id="webp"><a href="#webp" class="headerlink" title="webp"></a>webp</h4><p>支持纯透明和半透明，可以保证图片质量和较小的体积，适合Chrome和移动端浏览器。不适合其他浏览器。</p>
<h4 id="svg"><a href="#svg" class="headerlink" title="svg"></a>svg</h4><p>矢量格式，大小非常小，但渲染成本过高，适合小且色彩单一的图标。</p>
<h3 id="图片优化"><a href="#图片优化" class="headerlink" title="图片优化"></a>图片优化</h3><ul>
<li>减少图片资源的尺寸和大小，节约用户流量。</li>
<li>设置alt=”xxx”属性，图像无法显示时会显示alt内容。</li>
<li>图片懒加载， loading=”lazy”为原生，建议使用IntersectionObserver自己做懒加载。</li>
<li>不同环境加载不同尺寸和像素的图片srcset与sizes的使用。</li>
<li>采用渐进式加载 先加载占位图，然后加载模糊小图，最后加载真正清晰的图。</li>
<li>使用Base64URL 减少图片请求数。</li>
<li>采用雪碧图合并图片，减少请求数。</li>
</ul>
<h3 id="HTML优化"><a href="#HTML优化" class="headerlink" title="HTML优化"></a>HTML优化</h3><ul>
<li>语义化HTML，代码简洁清晰，利于SEO，便于开发维护。</li>
<li>减少HTML嵌套关系，减少DOM节点数量。</li>
<li>提前声明字符编码，让浏览器快速确定如何渲染网页内容<code>&lt;html lang="en"&gt; &lt;meta charset="UTF-8"&gt;</code>。</li>
<li>删除多余空格、空行、注释、无用属性。</li>
<li>减少iframe，子iframe会阻塞父级的onload事件。可以使用js动态给iframe赋值，就能解决这个问题。</li>
<li>避免table布局。</li>
</ul>
<h3 id="CSS优化"><a href="#CSS优化" class="headerlink" title="CSS优化"></a>CSS优化</h3><ul>
<li>减少伪类选择器，减少选择器层数、减少通配符选择器、减少正则选择器。</li>
<li>避免css表达式<code>background-color: expression(...)</code>。</li>
<li>删除空格、空行、注释、减少无意义的单位、css压缩。</li>
<li>css外链，能走缓存。</li>
<li>添加媒体字段，只加载有效的css文件。<figure class="highlight"><table><tbody><tr><td class="code"><pre><span class="line">&lt;link rel="stylesheet" href="./small.css" media="screen and (max-width:600px)" /&gt;</span><br><span class="line">&lt;link rel="stylesheet" href="./big.css" media="screen and (min-width:601px)"/&gt;</span><br></pre></td></tr></tbody></table></figure></li>
<li>使用css <code>contain</code>属性，能控制对应元素是否根据子集元素的改变进行重排。</li>
<li>减少<code>@import</code>使用，因为它使用串行加载。</li>
</ul>
<h3 id="JS优化"><a href="#JS优化" class="headerlink" title="JS优化"></a>JS优化</h3><ul>
<li>通过script的async、defer属性异步加载，不阻塞DOM渲染。</li>
<li>减少DOM操作，缓存访问过的元素。</li>
<li>不直接操作真实DOM，可以先修改，然后一次性应用到DOM上。（虚拟DOM、DOM碎片节点）。</li>
<li>使用webworker解决复杂运算，避免复杂运算阻塞主线程，webworker线程位于渲染进程。</li>
<li>图片懒加载，使用<code>IntersectionObserver</code>实现。</li>
</ul>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"IE=edge"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line">      img {</span><br><span class="line">        height: 200px;</span><br><span class="line">        display: block;</span><br><span class="line">      }</span><br><span class="line">    <span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./01.jpg"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./02.jpg"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./03.jpg"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./04.jpg"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./05.jpg"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./06.jpg"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./07.jpg"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./08.jpg"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./09.jpg"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"./loading.gif"</span> <span class="attr">data-src</span>=<span class="string">"./10.jpg"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> intersectionObserver = <span class="keyword">new</span> IntersectionObserver(<span class="function">(<span class="params">changes</span>) =&gt;</span> {</span></span><br><span class="line"><span class="javascript">        changes.forEach(<span class="function">(<span class="params">item, index</span>) =&gt;</span> {</span></span><br><span class="line"><span class="javascript">          <span class="keyword">if</span> (item.intersectionRatio &gt; <span class="number">0</span>) {</span></span><br><span class="line">            intersectionObserver.unobserve(item.target)</span><br><span class="line">            item.target.src = item.target.dataset.src</span><br><span class="line">          }</span><br><span class="line">        })</span><br><span class="line">      });</span><br><span class="line"></span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> domImgList = <span class="built_in">document</span>.querySelectorAll(<span class="string">"img"</span>);</span></span><br><span class="line"><span class="javascript">      domImgList.forEach(<span class="function">(<span class="params">domImg</span>) =&gt;</span> intersectionObserver.observe(domImg));</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>
<ul>
<li>虚拟滚动</li>
<li>使用<code>requestAnimationFrame</code>来做动画，使用<code>requestIdleCallback</code>来进行空闲时的任务处理。</li>
<li>尽量避免使用eval，性能差。</li>
<li>使用事件委托，能减少事件绑定个数。事件越多性能越差。</li>
<li>尽量使用canvas、css3动画。</li>
<li>通过chrome覆盖率（Coverage）工具排查代码中未使用过的代码并将其删除。</li>
<li>通过chrome性能（Performance）工具查看每个函数的执行性能并优化。</li>
</ul>
<h3 id="字体优化"><a href="#字体优化" class="headerlink" title="字体优化"></a>字体优化</h3><p>FOUT(Flash of Unstyled Text）等待一段时间，如果没加载完成，先显示默认。加载 后再进行切换。</p>
<p>FOIT(F1ash of Invisib1e Text） 字体加载完毕后显示，加载超时降级系统字体（白屏）。</p>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"IE=edge"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="css">    <span class="keyword">@font-face</span> {</span></span><br><span class="line">      font-family: 'hagan';</span><br><span class="line">      src: url('./font.ttc');</span><br><span class="line">      font-display: swap;</span><br><span class="line"><span class="css">      <span class="comment">/* b1ock 35 内不显示，如果没加载完毕用默认的 */</span></span></span><br><span class="line"><span class="css">      <span class="comment">/* swap 显示老字体 在替换*/</span></span></span><br><span class="line">      /* fa11back 缩短不显示时间，如果没加载完毕用默认的，和b1ock类似*</span><br><span class="line"><span class="css">      <span class="comment">/* optional 替换可能用字体 可能不替换*/</span></span></span><br><span class="line">    }</span><br><span class="line">    article {</span><br><span class="line">      font-family: hagan;</span><br><span class="line">    }</span><br><span class="line">  <span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">article</span>&gt;</span>ABC abc<span class="tag">&lt;/<span class="name">article</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>

<h2 id="浏览器储存优化策略"><a href="#浏览器储存优化策略" class="headerlink" title="浏览器储存优化策略"></a>浏览器储存优化策略</h2><h3 id="Cookie"><a href="#Cookie" class="headerlink" title="Cookie"></a>Cookie</h3><p><code>cookie</code>在过期之前一直有效，最大储存大小为4k，限制字段个数，不适合大量的数据储存，每次请求会携带<code>cookie</code>，主要用来做身份校验。</p>
<p>优化方式：</p>
<ol>
<li>需要合理设置<code>cookie</code>有效期。</li>
<li>根据不同子域划分<code>cookie</code>来减少<code>cookie</code>传输。</li>
<li>静态资源域名和<code>cookie</code>域名采用不同域名，避免静态资源请求携带<code>cookie</code>。</li>
</ol>
<h3 id="LocalStorage"><a href="#LocalStorage" class="headerlink" title="LocalStorage"></a>LocalStorage</h3><p>Chrome下最多储存5M，除非手动清除，否则一直存在。可以利用<code>localStorage</code>储存静态资源。比如储存网页的<code>.js</code>、<code>.css</code>，这样会使页面打开速度非常快。例如 <a target="_blank" rel="noopener" href="https://m.baidu.com/">https://m.baidu.com</a></p>
<figure class="highlight javascript"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">const</span> name = <span class="string">'hagan'</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">showName</span> (<span class="params"></span>) </span>{</span><br><span class="line">  <span class="built_in">console</span>.log(name)</span><br><span class="line">}</span><br><span class="line">showName()</span><br></pre></td></tr></tbody></table></figure>
<figure class="highlight html"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- index.html --&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"IE=edge"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://lib.baomitu.com/axios/0.26.1/axios.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">    cacheFile(<span class="string">'/index.js'</span>)</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">    <span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">cacheFile</span> (<span class="params">url</span>) </span>{</span></span><br><span class="line"><span class="javascript">      <span class="keyword">const</span> fileContent = <span class="built_in">localStorage</span>.getItem(url)</span></span><br><span class="line"><span class="javascript">      <span class="keyword">if</span> (fileContent) {</span></span><br><span class="line"><span class="javascript">        <span class="built_in">eval</span>(fileContent)</span></span><br><span class="line"><span class="javascript">      } <span class="keyword">else</span> {</span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> { data } = <span class="keyword">await</span> axios.get(url)</span></span><br><span class="line"><span class="javascript">        <span class="built_in">eval</span>(data)</span></span><br><span class="line"><span class="javascript">        <span class="built_in">localStorage</span>.setItem(url, data)</span></span><br><span class="line">      }</span><br><span class="line">    }</span><br><span class="line">  <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></tbody></table></figure>
<h3 id="SessionStorage"><a href="#SessionStorage" class="headerlink" title="SessionStorage"></a>SessionStorage</h3><p>会话级别储存，可用于页面间的传值。</p>
<h3 id="IndexDB"><a href="#IndexDB" class="headerlink" title="IndexDB"></a>IndexDB</h3><p>浏览器的本地数据库，大小几乎无上限。</p>
<h2 id="其他优化策略"><a href="#其他优化策略" class="headerlink" title="其他优化策略"></a>其他优化策略</h2><ul>
<li>关键资源个数越多，首次页面加载时间就会越长。</li>
<li>关键资源的大小，内容越小下载时间越短。</li>
<li>优化白屏，合理使用内联css、js。</li>
<li>预渲染，打包时进行预渲染，生成静态HTML文件，用户访问时直接返回静态HTML。</li>
<li>服务端渲染同构，加速首屏速度（耗费服务端资源），有利于SEO优化。首屏使用服务端渲染，后续交互使用客户端渲染。</li>
</ul>
<h2 id="使用PWA提高用户体验"><a href="#使用PWA提高用户体验" class="headerlink" title="使用PWA提高用户体验"></a>使用PWA提高用户体验</h2><p>webapp用户体验差的一大原因是不能离线访问。用户粘性低的一大原因是无法保存入口，PWA就是为了解决webapp的用户体验问题而诞生的。使用PWA能令站点拥有快速、可靠、安全等特性。</p>
<ol>
<li>Web App Manifest 将网站添加到电脑桌面、手机桌面，类似Native的体验。</li>
<li>Service Worker 配合Cache API，能做到离线缓存各种内容。</li>
<li>Push API 配合 Notification API，能做到类似Native的消息推送与实时提醒。</li>
<li>App Shell 配合 App Skeleton，能做App壳与骨架屏。</li>
</ol>
<!-- <div class="note info flat"><p>原文链接：<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/wJxj5QbOHwH9cKmqU5eSQw">Web页面全链路性能优化指南</a></p>
</div> --></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://fe32.top">Ethan.Tzy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://fe32.top/articles/we0522bs/">https://fe32.top/articles/we0522bs/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://fe32.top" target="_blank">唐志远の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/@3.7.1/tags/Web%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">Web性能优化</a></div><div class="post_share"><div class="social-share" data-image="https://bu.dusays.com/2022/05/02/626ec4fa5cc28.png" data-sites="facebook,twitter,google,wechat,weibo,qq"></div><link rel="stylesheet" href="https://npm.elemecdn.com/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://bu.dusays.com/2022/05/17/6283c3f127558.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://bu.dusays.com/2022/05/17/6283c3f127558.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://bu.dusays.com/2022/05/17/6283c3ee6d872.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://bu.dusays.com/2022/05/17/6283c3ee6d872.jpg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/@3.7.1/articles/vu9856es/"><img class="prev-cover" data-lazy-src="https://bu.dusays.com/2022/05/16/628126df2eb49.png" onerror="onerror=null;src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">7个 Vue3 中的组件通信方式</div></div></a></div><div class="next-post pull-right"><a href="/@3.7.1/articles/hexo1602/"><img class="next-cover" data-lazy-src="https://bu.dusays.com/2022/05/25/628d12bdec61c.png" onerror="onerror=null;src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">基于 Hexo 从零开始搭建个人博客（二）</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/@3.7.1/articles/we0523bs/" title="浅谈性能优化之图片压缩、加载和格式选择"><img class="cover" data-lazy-src="https://bu.dusays.com/2022/10/23/635504c13b152.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-23</div><div class="title">浅谈性能优化之图片压缩、加载和格式选择</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" onerror="this.onerror=null;this.src='https://bu.dusays.com/2021/03/27/0106da541a922.gif'" alt="avatar"/><div class="author-info__name">Ethan.Tzy</div><div class="author-info__description">2023年的理想开始实现了吗？</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/@3.7.1/archives/"><div class="headline">文章</div><div class="length-num">101</div></a></div><div class="card-info-data-item is-center"><a href="/@3.7.1/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div><div class="card-info-data-item is-center"><a href="/@3.7.1/categories/"><div class="headline">分类</div><div class="length-num">20</div></a></div></div><div class="card-info-social-icons is-center"><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2938526863&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://bu.dusays.com/2022/05/17/6283c39fcfc2f.png" target="_blank" title="Wechat"><i class="fab fa-weixin"></i></a><a class="social-icon" href="mailto:ethan4116@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://github.com/tzy13755126023" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="/@3.7.1/atom.xml" target="_blank" title="Rss"><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content"><div style='text-indent:2em'>本站只保留入口，即将不再更新内容，请切换成回最新版本。</div><div id="qq-btn"><a id="a-qun" href="https://fe32.top/" target="_blank">回最新版本 ✨</a></div><div id="qq-btn" style="margin-top:10px"><a id="a-qun" href="https://qm.qq.com/cgi-bin/qm/qr?k=IqfyAyFpCIMln6xPXkjkI_gzF8zx29zK&jump_from=webapi&authKey=jcME5f+e8XES0vAaUTAaI24tsgUMdoIZ0oGwAOoHNpK1HSWdcI9zmSlWVdfw/ax+" target="_blank">加入QQ群 ✨</a></div></div></div><div class="card-widget tzy-right-widget" id="card-wechat"><div id="flip-wrapper"><div id="flip-content"><div class="face"></div><div class="back face"></div></div></div></div><div class="xpand" style="height:200px;"><canvas class="illo" width="800" height="800" style="max-width: 200px; max-height: 200px; touch-action: none; width: 640px; height: 640px;"></canvas></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E6%B8%B2%E6%9F%93%E5%8E%9F%E7%90%86"><span class="toc-number">1.</span> <span class="toc-text">浏览器渲染原理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%9B%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B"><span class="toc-number">1.1.</span> <span class="toc-text">进程与线程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BE%93%E5%85%A5url%E5%88%B0%E9%A1%B5%E9%9D%A2%E5%B1%95%E7%A4%BA%E5%AE%8C%E6%95%B4%E8%BF%87%E7%A8%8B"><span class="toc-number">1.2.</span> <span class="toc-text">输入url到页面展示完整过程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8%E6%88%B7%E8%BE%93%E5%85%A5"><span class="toc-number">1.2.1.</span> <span class="toc-text">用户输入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%B8%E8%BD%BD%E5%8E%9F%E9%A1%B5%E9%9D%A2%E5%B9%B6%E9%87%8D%E5%AE%9A%E5%90%91%E5%88%B0%E6%96%B0%E9%A1%B5%E9%9D%A2"><span class="toc-number">1.2.2.</span> <span class="toc-text">卸载原页面并重定向到新页面</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%84%E7%90%86Service-Worker"><span class="toc-number">1.2.3.</span> <span class="toc-text">处理Service Worker</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82"><span class="toc-number">1.2.4.</span> <span class="toc-text">网络请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%93%8D%E5%BA%94"><span class="toc-number">1.2.5.</span> <span class="toc-text">服务端响应</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E6%B8%B2%E6%9F%93%E8%AF%A6%E7%BB%86%E6%B5%81%E7%A8%8B"><span class="toc-number">1.2.6.</span> <span class="toc-text">浏览器渲染详细流程</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90HTML%E3%80%91"><span class="toc-number">1.2.6.1.</span> <span class="toc-text">【HTML】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90HTML-Parser%E3%80%91"><span class="toc-number">1.2.6.2.</span> <span class="toc-text">【HTML Parser】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90DOM-Tree%E3%80%91"><span class="toc-number">1.2.6.3.</span> <span class="toc-text">【DOM Tree】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90Style-Sheets%E3%80%91"><span class="toc-number">1.2.6.4.</span> <span class="toc-text">【Style Sheets】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90CSS-Parser%E3%80%91"><span class="toc-number">1.2.6.5.</span> <span class="toc-text">【CSS Parser】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90Style-Rules%E3%80%91"><span class="toc-number">1.2.6.6.</span> <span class="toc-text">【Style Rules】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90Attachment%E3%80%91"><span class="toc-number">1.2.6.7.</span> <span class="toc-text">【Attachment】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90Render-Tree%E3%80%91"><span class="toc-number">1.2.6.8.</span> <span class="toc-text">【Render Tree】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90Layout%E3%80%91"><span class="toc-number">1.2.6.9.</span> <span class="toc-text">【Layout】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90Painting%E3%80%91"><span class="toc-number">1.2.6.10.</span> <span class="toc-text">【Painting】</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90Display%E3%80%91"><span class="toc-number">1.2.6.11.</span> <span class="toc-text">【Display】</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E5%A4%84%E7%90%86%E6%AF%8F%E4%B8%80%E5%B8%A7%E7%9A%84%E6%B5%81%E7%A8%8B"><span class="toc-number">1.3.</span> <span class="toc-text">浏览器处理每一帧的流程</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Chrome%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%9B%B8%E5%85%B3%E5%B7%A5%E5%85%B7"><span class="toc-number">2.</span> <span class="toc-text">Chrome性能优化相关工具</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Chrome-Performance-%E6%80%A7%E8%83%BD"><span class="toc-number">2.1.</span> <span class="toc-text">Chrome Performance(性能)</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Chrome-Performance-%E5%B7%A5%E5%85%B7%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-number">2.1.1.</span> <span class="toc-text">Chrome Performance 工具的使用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Performance-API%E4%BB%8B%E7%BB%8D"><span class="toc-number">2.1.2.</span> <span class="toc-text">Performance API介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8Performance-API%E8%8E%B7%E5%8F%96%E6%80%A7%E8%83%BD%E7%9B%B8%E5%85%B3%E6%8C%87%E6%A0%87"><span class="toc-number">2.1.3.</span> <span class="toc-text">使用Performance API获取性能相关指标</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#TTFB-%E9%A6%96%E5%AD%97%E8%8A%82%E6%97%B6%E9%97%B4"><span class="toc-number">2.1.3.1.</span> <span class="toc-text">TTFB 首字节时间</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#FP-%E9%A6%96%E6%AC%A1%E7%BB%98%E5%88%B6"><span class="toc-number">2.1.3.2.</span> <span class="toc-text">FP 首次绘制</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#FCP-%E9%A6%96%E6%AC%A1%E5%86%85%E5%AE%B9%E7%BB%98%E5%88%B6"><span class="toc-number">2.1.3.3.</span> <span class="toc-text">FCP 首次内容绘制</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#FMP-%E9%A6%96%E6%AC%A1%E6%9C%89%E6%95%88%E7%BB%98%E5%88%B6"><span class="toc-number">2.1.3.4.</span> <span class="toc-text">FMP 首次有效绘制</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#TTI-%E5%8F%AF%E4%BA%A4%E4%BA%92%E6%97%B6%E9%97%B4"><span class="toc-number">2.1.3.5.</span> <span class="toc-text">TTI 可交互时间</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#LCP-%E6%9C%80%E5%A4%A7%E5%86%85%E5%AE%B9%E6%B8%B2%E6%9F%93"><span class="toc-number">2.1.3.6.</span> <span class="toc-text">LCP  最大内容渲染</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DCL"><span class="toc-number">2.1.3.7.</span> <span class="toc-text">DCL</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#L-%E5%85%A8%E9%83%A8%E5%8A%A0%E8%BD%BD%E5%AE%8C%E6%AF%95"><span class="toc-number">2.1.3.8.</span> <span class="toc-text">L 全部加载完毕</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#FID-%E9%A6%96%E6%AC%A1%E8%BE%93%E5%85%A5%E5%BB%B6%E8%BF%9F"><span class="toc-number">2.1.3.9.</span> <span class="toc-text">FID 首次输入延迟</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#TBT-%E9%A1%B5%E9%9D%A2%E9%98%BB%E5%A1%9E%E6%80%BB%E6%97%B6%E9%95%BF"><span class="toc-number">2.1.3.10.</span> <span class="toc-text">TBT 页面阻塞总时长</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CLS-%E7%B4%AF%E7%A7%AF%E5%B8%83%E5%B1%80%E5%81%8F%E7%A7%BB"><span class="toc-number">2.1.3.11.</span> <span class="toc-text">CLS 累积布局偏移</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#SI"><span class="toc-number">2.1.3.12.</span> <span class="toc-text">SI</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Coverage-%E8%A6%86%E7%9B%96%E7%8E%87"><span class="toc-number">2.2.</span> <span class="toc-text">Coverage(覆盖率)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lighthouse"><span class="toc-number">2.3.</span> <span class="toc-text">Lighthouse</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Network-%E7%BD%91%E7%BB%9C"><span class="toc-number">2.4.</span> <span class="toc-text">Network(网络)</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E4%B8%AD%E7%9A%84Timing-%E6%97%B6%E9%97%B4"><span class="toc-number">2.4.1.</span> <span class="toc-text">网络请求中的Timing(时间)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E7%9A%84%E4%BC%98%E5%85%88%E7%BA%A7"><span class="toc-number">2.4.2.</span> <span class="toc-text">网络请求的优先级</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E9%A1%B5%E6%80%BB%E8%B5%84%E6%BA%90%E4%BF%A1%E6%81%AF"><span class="toc-number">2.4.3.</span> <span class="toc-text">网页总资源信息</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Network%E9%85%8D%E7%BD%AE"><span class="toc-number">2.4.4.</span> <span class="toc-text">Network配置</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BD%91%E9%A1%B5%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96"><span class="toc-number">3.</span> <span class="toc-text">网页性能优化</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E4%BC%98%E5%8C%96%E7%AD%96%E7%95%A5"><span class="toc-number">3.1.</span> <span class="toc-text">网络优化策略</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%8F%E5%B0%91HTTP%E8%AF%B7%E6%B1%82%E6%95%B0"><span class="toc-number">3.1.1.</span> <span class="toc-text">减少HTTP请求数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8HTTP%E7%BC%93%E5%AD%98"><span class="toc-number">3.1.2.</span> <span class="toc-text">使用HTTP缓存</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-HTTP-2-0"><span class="toc-number">3.1.3.</span> <span class="toc-text">使用 HTTP&#x2F;2.0</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%81%BF%E5%85%8D%E9%87%8D%E5%AE%9A%E5%90%91"><span class="toc-number">3.1.4.</span> <span class="toc-text">避免重定向</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-dns-prefetch"><span class="toc-number">3.1.5.</span> <span class="toc-text">使用 dns-prefetch</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%9F%9F%E5%90%8D%E5%88%86%E7%89%87"><span class="toc-number">3.1.6.</span> <span class="toc-text">使用域名分片</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#CDN"><span class="toc-number">3.1.7.</span> <span class="toc-text">CDN</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8E%8B%E7%BC%A9"><span class="toc-number">3.1.8.</span> <span class="toc-text">压缩</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8contenthash"><span class="toc-number">3.1.9.</span> <span class="toc-text">使用contenthash</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%88%E7%90%86%E4%BD%BF%E7%94%A8preload%E3%80%81prefetch"><span class="toc-number">3.1.10.</span> <span class="toc-text">合理使用preload、prefetch</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E6%B8%B2%E6%9F%93%E4%BC%98%E5%8C%96%E7%AD%96%E7%95%A5"><span class="toc-number">3.2.</span> <span class="toc-text">浏览器渲染优化策略</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B3%E9%94%AE%E6%B8%B2%E6%9F%93%E8%B7%AF%E5%BE%84"><span class="toc-number">3.2.1.</span> <span class="toc-text">关键渲染路径</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%BA%E5%88%B6%E5%90%8C%E6%AD%A5%E5%B8%83%E5%B1%80%E9%97%AE%E9%A2%98"><span class="toc-number">3.2.2.</span> <span class="toc-text">强制同步布局问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E5%87%8F%E5%B0%91%E9%87%8D%E6%8E%92%E4%B8%8E%E9%87%8D%E7%BB%98"><span class="toc-number">3.2.3.</span> <span class="toc-text">如何减少重排与重绘</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9D%99%E6%80%81%E6%96%87%E4%BB%B6%E4%BC%98%E5%8C%96%E7%AD%96%E7%95%A5"><span class="toc-number">3.3.</span> <span class="toc-text">静态文件优化策略</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%BE%E7%89%87%E6%A0%BC%E5%BC%8F"><span class="toc-number">3.3.1.</span> <span class="toc-text">图片格式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#jpeg"><span class="toc-number">3.3.1.1.</span> <span class="toc-text">jpeg</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#png"><span class="toc-number">3.3.1.2.</span> <span class="toc-text">png</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#gif"><span class="toc-number">3.3.1.3.</span> <span class="toc-text">gif</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#webp"><span class="toc-number">3.3.1.4.</span> <span class="toc-text">webp</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#svg"><span class="toc-number">3.3.1.5.</span> <span class="toc-text">svg</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%BE%E7%89%87%E4%BC%98%E5%8C%96"><span class="toc-number">3.3.2.</span> <span class="toc-text">图片优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#HTML%E4%BC%98%E5%8C%96"><span class="toc-number">3.3.3.</span> <span class="toc-text">HTML优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#CSS%E4%BC%98%E5%8C%96"><span class="toc-number">3.3.4.</span> <span class="toc-text">CSS优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JS%E4%BC%98%E5%8C%96"><span class="toc-number">3.3.5.</span> <span class="toc-text">JS优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%97%E4%BD%93%E4%BC%98%E5%8C%96"><span class="toc-number">3.3.6.</span> <span class="toc-text">字体优化</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E5%82%A8%E5%AD%98%E4%BC%98%E5%8C%96%E7%AD%96%E7%95%A5"><span class="toc-number">3.4.</span> <span class="toc-text">浏览器储存优化策略</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Cookie"><span class="toc-number">3.4.1.</span> <span class="toc-text">Cookie</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#LocalStorage"><span class="toc-number">3.4.2.</span> <span class="toc-text">LocalStorage</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SessionStorage"><span class="toc-number">3.4.3.</span> <span class="toc-text">SessionStorage</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#IndexDB"><span class="toc-number">3.4.4.</span> <span class="toc-text">IndexDB</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B6%E4%BB%96%E4%BC%98%E5%8C%96%E7%AD%96%E7%95%A5"><span class="toc-number">3.5.</span> <span class="toc-text">其他优化策略</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8PWA%E6%8F%90%E9%AB%98%E7%94%A8%E6%88%B7%E4%BD%93%E9%AA%8C"><span class="toc-number">3.6.</span> <span class="toc-text">使用PWA提高用户体验</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/joy10001/" title="被发现了，这些吊炸天的摸鱼网站！"><img data-lazy-src="https://bu.dusays.com/2023/06/18/648f1359dc90f.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="被发现了，这些吊炸天的摸鱼网站！"/></a><div class="content"><a class="title" href="/@3.7.1/articles/joy10001/" title="被发现了，这些吊炸天的摸鱼网站！">被发现了，这些吊炸天的摸鱼网站！</a><time datetime="2023-06-18T16:40:07.000Z" title="发表于 2023-06-19 00:40:07">2023-06-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/vue20002/" title="解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题"><img data-lazy-src="https://bu.dusays.com/2023/06/18/648ed3f987511.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题"/></a><div class="content"><a class="title" href="/@3.7.1/articles/vue20002/" title="解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题">解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题</a><time datetime="2023-06-18T16:20:32.000Z" title="发表于 2023-06-19 00:20:32">2023-06-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/hexo1619/" title="如何新窗口打开导航链接？"><img data-lazy-src="https://bu.dusays.com/2023/06/04/647c9bb365e09.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="如何新窗口打开导航链接？"/></a><div class="content"><a class="title" href="/@3.7.1/articles/hexo1619/" title="如何新窗口打开导航链接？">如何新窗口打开导航链接？</a><time datetime="2023-06-04T13:53:07.000Z" title="发表于 2023-06-04 21:53:07">2023-06-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/ts30001/" title="一文读懂TS的(.d.ts)文件"><img data-lazy-src="https://bu.dusays.com/2023/04/29/644d384035bca.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="一文读懂TS的(.d.ts)文件"/></a><div class="content"><a class="title" href="/@3.7.1/articles/ts30001/" title="一文读懂TS的(.d.ts)文件">一文读懂TS的(.d.ts)文件</a><time datetime="2023-04-30T14:28:06.000Z" title="发表于 2023-04-30 22:28:06">2023-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/vue20001/" title="Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法"><img data-lazy-src="https://bu.dusays.com/2023/04/29/644d249bc9001.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法"/></a><div class="content"><a class="title" href="/@3.7.1/articles/vue20001/" title="Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法">Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法</a><time datetime="2023-04-30T12:34:18.000Z" title="发表于 2023-04-30 20:34:18">2023-04-30</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://bu.dusays.com/2021/03/06/34d960d18cd54.jpg')"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">公益广告</p><div class="bg-ad"><div>国家反诈中心是国务院打击治理电信网络新型违法犯罪工作部际联席会议合成作战平台，集资源整合、情报研判、侦查指挥为一体，在打击、防范、治理电信网络诈骗等新型违法犯罪中发挥着重要作用。</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://www.hack-gov.com.cn/posts/21480.html">下载（国家反诈中心） APP</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">修仙导航</p><ul class="ft-links"><li><a target="_blank" rel="noopener" href="https://tzy1997.com/articles/hexo1600/">建站指南</a><a target="_blank" rel="noopener" href="https://tzy1997.com/nav.html">网址导航</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/sponsorWall/">来杯咖啡</a><a target="_blank" rel="noopener" href="https://tzy1997.com/comments/">留点什么</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/about/">关于博主</a><a target="_blank" rel="noopener" href="https://tzy1997.com/archives/">文章归档</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/categories/">文章分类</a><a target="_blank" rel="noopener" href="https://tzy1997.com/tags/">文章标签</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/gallery/">我的相册</a><a target="_blank" rel="noopener" href="https://tzy1997.com/bangumis/">我的追番</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/specialEffects/">一些特效</a><a target="_blank" rel="noopener" href="https://tzy1997.com/wallpaper/">一些壁纸</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链</p><div class="ft-img-group"><div class="img-group-item"><a target="_blank" rel="noopener" href="https://tzy1997.com/"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://blog.zhheo.com/"><img src="https://npm.elemecdn.com/guli-heo/img/avatar2.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.thyuu.com/"><img src="https://npm.elemecdn.com/imgscdn/img/202111191951780.JPG" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://dusays.com/"><img src="https://cdn.dusays.com/avatar.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://akilar.top/"><img src="https://npm.elemecdn.com/akilar-candyassets/image/siteicon/favicon.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.fomal.cc/"><img src="https://bu.dusays.com/2022/11/06/6367af8667f0e.webp" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.startly.cn/"><img src="https://bu.dusays.com/2023/04/15/643a99cb740a4.jpg" alt=""/></a></div><div class="img-group-item"><a href="javascript:btf.snackbarShow(&quot;预留友链位~~&quot;)"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" alt=""/></a></div></div></div></div><div class="copyright">&copy;2020 - 2023  <i id="heartbeat" class="fa fas fa-heartbeat"></i> Ethan.Tzy</div><div class="footer_custom_text">I wish you to become your own sun, no need to rely on who's light.✨✨✨<p><a target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a>&nbsp;<a target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a>&nbsp;<a target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a> &nbsp;<a target="_blank" href="https://vercel.com/ "><img src="https://img.shields.io/badge/Hosted-Vervel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a>&nbsp;<a target="_blank" href="https://icp.gov.moe/?keyword=20220686" title="本站已加入萌ICP豪华套餐，萌ICP备20220686号"><img src="https://img.shields.io/badge/%E8%90%8CICP%E5%A4%87-20220686-fe1384?style-flat&amp;logo="></a>&nbsp;<a target="_blank" href="https://vercel.com/"><img src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a>&nbsp;<a target="_blank" href="https://github.com/"><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a>&nbsp;<a target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="在线聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuPlugin"><div class="rightMenu-item" id="menu-copytext"><i class="fa-solid fa-copy"></i><span>复制文本</span></div><div class="rightMenu-item" id="menu-newwindow"><i class="fa-solid fa-window-restore"></i><span>新窗口打开</span></div><div class="rightMenu-item" id="menu-copylink"><i class="fa-solid fa-copy"></i><span>复制链接地址</span></div><div class="rightMenu-item" id="menu-copyimg"><i class="fa-solid fa-copy"></i><span>复制图片</span></div><div class="rightMenu-item" id="menu-downloadimg"><i class="fa-solid fa-download"></i><span>下载图片</span></div><div class="rightMenu-item" id="menu-search"><i class="fa-solid fa-magnifying-glass"></i><span>站内搜索</span></div><div class="rightMenu-item" id="menu-searchBaidu"><i class="fa-solid fa-magnifying-glass"></i><span>百度搜索</span></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><div class="rightMenu-item" id="menu-radompage"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></div><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a><a class="rightMenu-item" id="menu-goto-comment" href="#post-comment"><i class="fas fa-comment"></i><span>空降评论</span></a><a class="rightMenu-item menu-link" href="/sponsorWall/"><i class="fa-solid fa-money-check-alt"></i><span>赞助墙</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-readmode"><i class="fa-solid fa-book-open"></i><span>阅读模式</span></div><div class="rightMenu-item" id="menu-print"><i class="fa-solid fa-print fa-fw"></i><span>打印页面</span></div><div class="rightMenu-item" id="menu-copy"><i class="fa-solid fa-share"></i><span>分享本页</span></div></div></div><div id="rightmenu-mask"></div><div id="myscoll"></div><div><script src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script src="/@3.7.1/"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/utils.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/main.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/tw_cn.js"></script><script src="https://npm.elemecdn.com/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/search/algolia.js"></script><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())
setTimeout(function(){preloader.endLoading();}, 5000);</script><div class="js-pjax"><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo.fe32.top/',
      region: '',
      onCommentLoaded: function () {
        //- const ele = document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)')
      }
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'https://twikoo.fe32.top/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://fastly.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'https://twikoo.fe32.top/',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://fastly.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (true) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><div class="pjax-reload"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '1s');
    arr[i].setAttribute('data-wow-delay', '1s');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('site-card');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__flipInY');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '100ms');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('github-badge');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__flipInX');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '100ms');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer="defer" src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/wow.min.js"></script><script defer="defer" src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/wow_init.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/cat.js"></script><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/issues.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/twopeople1.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/zdog.dist.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/twopeople.js"></script><canvas id="universe"></canvas><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/universe.js"></script><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/ethan_tzy.js"></script><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/right-menu/rightMenu@3.7.1.js"></script><script async src="//at.alicdn.com/t/font_2315348_g8vs01iykv.js"></script><script async src="https://www.googletagmanager.com/gtag/js?id=G-92YZLM7C2B"></script><script> window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', 'G-92YZLM7C2B');</script><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9697737937582017" crossorigin="anonymous"></script><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "https://hm.baidu.com/hm.js?bbcbaf179f87d03d28c3ba72c79a5640";var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s);})();</script><script>!function(p){"use strict";!function(t){var s=window,e=document,i=p,c="".concat("https:"===e.location.protocol?"https://":"http://","sdk.51.la/js-sdk-pro.min.js"),n=e.createElement("script"),r=e.getElementsByTagName("script")[0];n.type="text/javascript",n.setAttribute("charset","UTF-8"),n.async=!0,n.src=c,n.id="LA_COLLECT",i.d=n;var o=function(){s.LA.ids.push(i)};s.LA?s.LA.ids&&o():(s.LA=p,s.LA.ids=[],o()),r.parentNode.insertBefore(n,r)}()}({id:"Jo9JJAc5cBaxwwnJ",ck:"Jo9JJAc5cBaxwwnJ"});</script><script src="https://npm.elemecdn.com/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://npm.elemecdn.com/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script>window.$crisp = [];
window.CRISP_WEBSITE_ID = "58b8ce9e-19e0-46ff-8e8d-6ee1b1b25c45";
(function () {
  d = document;
  s = d.createElement("script");
  s.src = "https://client.crisp.chat/l.js";
  s.async = 1;
  d.getElementsByTagName("head")[0].appendChild(s);
})();
$crisp.push(["safe", true])

if (true) {
  $crisp.push(["do", "chat:hide"])
  $crisp.push(["on", "chat:closed", function() {
    $crisp.push(["do", "chat:hide"])
  }])
  var chatBtnFn = () => {
    var chatBtn = document.getElementById("chat_btn")
    chatBtn.addEventListener("click", function(){
      $crisp.push(["do", "chat:show"])
      $crisp.push(["do", "chat:open"])

    });
  }
  chatBtnFn()
} else {
  if (false) {
    function chatBtnHide () {
      $crisp.push(["do", "chat:hide"])
    }
    function chatBtnShow () {
      $crisp.push(["do", "chat:show"])
    }
  }
}</script><link rel="stylesheet" href="https://npm.elemecdn.com/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/aplayer/dist/APlayer.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/meting.min.js"></script><script src="https://npm.elemecdn.com/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener toc scroll 
  window.removeEventListener('scroll', window.tocScrollFn)

  typeof preloader === 'object' && preloader.initLoading()

  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  //- document.querySelectorAll('script[data-pjax]').forEach(item => {
  
  document.querySelectorAll('script[data-pjax], .pjax-reload script').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})


//- document.addEventListener('pjax:send', function () {
//-   typeof preloader === 'object' && preloader.initLoading()
  
//-   if (window.aplayers) {
//-     for (let i = 0; i < window.aplayers.length; i++) {
//-       if (!window.aplayers[i].options.fixed) {
//-         window.aplayers[i].destroy()
//-       }
//-     }
//-   }

//-   typeof typed === 'object' && typed.destroy()

//-   //reset readmode
//-   const $bodyClassList = document.body.classList
//-   $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

//- })

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    if (false) {
      location.hash && e.request.responseURL !== location.href ? pjax.loadUrl(location.href) : pjax.loadUrl('/404.html')
      return
    }
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>